package com.zhk.entry.proxy;


import com.zhk.entry.observer.SprotSubject;
import com.zhk.entry.util.IThreadConn;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Observer;

public class StuInvocationHandler<T> implements InvocationHandler {

    private T target;

    private IThreadConn iThreadConn;

//    private  SprotSubject sprotSubject = new SprotSubject();

    public StuInvocationHandler(T target) {
        this.target = target;
//        sprotSubject.addObserver((Observer) target);
    }


    public StuInvocationHandler(T target, IThreadConn iThreadConn) {
        this.target = target;
        this.iThreadConn = iThreadConn;

    }


    @Override
    public Object invoke(Object o, Method method, Object[] args) {
        Object object = null;
        try {
            System.out.println("代理：前置的增强");
            object = (T) method.invoke(target, args);
            int i = 1 / 0;
            //提交事务
            System.out.println("代理：后置的增强");
//            sprotSubject.addNews("commit");
        } catch (Exception e) {
            e.printStackTrace();
            //事务回滚
//            sprotSubject.addNews("rollback");
            System.out.println("代理：异常的处理");
        }
        return object;
    }

    public T createProxy() {
        T proxy = (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new StuInvocationHandler<T>(target));
        return proxy;
    }

}
